<template>
    <!-- 事实外包方编辑页面 -->
    <div class="e-form">
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="委托人"
                    name="client"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="rules"
                                        ref="formData"
                                    >
                                      <BillTop title="事实外包方变更编辑" @cancel="handleClose"></BillTop>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="统一社会信用代码"
                                                    prop="creditCode"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.creditCode
                                                        "
                                                        maxlength="18"
                                                    ></el-input>

                                                    <el-button type="primary"
                                                        >验证</el-button
                                                    >
                                                    <img
                                                        v-if="
                                                            oldEditData.creditCode &&
                                                            formData.creditCode &&
                                                            oldEditData.creditCode !=
                                                                formData.creditCode
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="外包方类别"
                                                    prop="type"
                                                >
                                                    <el-radio-group
                                                        v-model="formData.type"
                                                    >
                                                        <el-radio :label="0"
                                                            >分包商</el-radio
                                                        >
                                                        <el-radio :label="1"
                                                            >供应商</el-radio
                                                        >
                                                    </el-radio-group>
                                                    <img
                                                        v-if="
                                                            oldEditData.type &&
                                                            formData.type &&
                                                            oldEditData.type !=
                                                                formData.type
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="外包方名称："
                                                    prop="outerName"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.outerName
                                                        "
                                                    ></el-input>
                                                    <img
                                                        v-if="
                                                            oldEditData.outerName &&
                                                            formData.outerName &&
                                                            oldEditData.outerName !=
                                                                formData.outerName
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="法人代表"
                                                    prop="deputy"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.deputy
                                                        "
                                                    ></el-input>
                                                    <img
                                                        v-if="
                                                            oldEditData.deputy &&
                                                            formData.deputy &&
                                                            oldEditData.deputy !=
                                                                formData.deputy
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="法人身份证号码："
                                                    prop="idCard"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.idCard
                                                        "
                                                        maxlength="18"
                                                    ></el-input>
                                                    <img
                                                        v-if="
                                                            oldEditData.idCard &&
                                                            formData.idCard &&
                                                            oldEditData.idCard !=
                                                                formData.idCard
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="法人身份证附件"
                                                    prop="deputyOssName"
                                                >
                                                    <span
                                                        @click="preview1()"
                                                        style="
                                                            disply: inline-block;
                                                            width: 100%;
                                                            color: blue;
                                                            cursor: pointer;
                                                            overflow: hidden;
                                                        "
                                                        >{{
                                                            formData.deputyOssName
                                                        }}</span
                                                    >
                                                    <el-upload
                                                        style="
                                                            margin: 7px 5px 0px
                                                                0px;
                                                        "
                                                        class="upload-demo"
                                                        :action="uploadUrl"
                                                        :data="{
                                                            bucketName,
                                                            relationId,
                                                            orgCode
                                                        }"
                                                        :before-upload="
                                                            beforeAvatarUpload
                                                        "
                                                        :accept="accept"
                                                        :on-success="
                                                            attachOnSuccess
                                                        "
                                                        :http-request="
                                                            uploadBefore
                                                        "
                                                        :show-file-list="false"
                                                        name="files"
                                                    >
                                                        <el-button
                                                            type="primary"
                                                            >上传</el-button
                                                        >
                                                    </el-upload>
                                                    <img
                                                        v-if="
                                                            oldEditData.deputyOssName &&
                                                            formData.deputyOssName &&
                                                            oldEditData.deputyOssName !=
                                                                formData.deputyOssName
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="注册资本(万元)："
                                                    prop="registeredCapital"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.registeredCapital
                                                        "
                                                        v-enterFloat2
                                                    ></el-input>
                                                    <img
                                                        v-if="
                                                            oldEditData.registeredCapital &&
                                                            formData.registeredCapital &&
                                                            oldEditData.registeredCapital !=
                                                                formData.registeredCapital
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="营业执照"
                                                    prop="businessLicenseOssName"
                                                >
                                                    <span
                                                        @click="preview2()"
                                                        style="
                                                            disply: inline-block;
                                                            width: 100%;
                                                            color: blue;
                                                            cursor: pointer;
                                                            overflow: hidden;
                                                        "
                                                        >{{
                                                            formData.businessLicenseOssName
                                                        }}</span
                                                    >
                                                    <el-upload
                                                        style="
                                                            margin: 7px 5px 0px
                                                                0px;
                                                        "
                                                        class="upload-demo"
                                                        :action="uploadUrl"
                                                        :data="{
                                                            bucketName,
                                                            relationId,
                                                            orgCode
                                                        }"
                                                        :before-upload="
                                                            beforeAvatarUpload
                                                        "
                                                        :accept="accept"
                                                        :on-success="
                                                            attachOnSuccessBl
                                                        "
                                                        :http-request="
                                                            uploadBeforeBl
                                                        "
                                                        :show-file-list="false"
                                                        name="files"
                                                    >
                                                        <el-button
                                                            type="primary"
                                                            >上传</el-button
                                                        >
                                                    </el-upload>
                                                    <img
                                                        v-if="
                                                            oldEditData.businessLicenseOssName &&
                                                            formData.businessLicenseOssName &&
                                                            oldEditData.businessLicenseOssName !=
                                                                formData.businessLicenseOssName
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="库外单位">
                                                    <el-switch
                                                        :width="60"
                                                        v-model="
                                                            formData.isOutOrg
                                                        "
                                                        class="main-el-switch"
                                                        active-color="#13ce66"
                                                        inactive-color="#D2D2D2"
                                                        active-value="1"
                                                        inactive-value="0"
                                                        active-text="是"
                                                        inactive-text="否"
                                                    >
                                                    </el-switch>
                                                    <img
                                                        v-if="
                                                            oldEditData.isOutOrg &&
                                                            formData.isOutOrg &&
                                                            oldEditData.isOutOrg !=
                                                                formData.isOutOrg
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="录入机构"
                                                    >{{
                                                        formData.orgName
                                                    }}</el-form-item
                                                >
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="注册地址"
                                                    prop="address"
                                                >
                                                    <SelectAddr
                                                        v-model="
                                                            formData.address
                                                        "
                                                        lazy
                                                        showCountry
                                                        style="width: 100%"
                                                    ></SelectAddr>
                                                    <img
                                                        v-if="
                                                            oldEditData.address &&
                                                            formData.address &&
                                                            oldEditData.address !=
                                                                formData.address
                                                        "
                                                        class="img-style"
                                                        src="@/assets/biangeng.png"
                                                        alt=""
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        statusLable(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 委托人 -->
                    <div id="clientCon" class="con">
                        <div class="tabs-title" id="client">委托人</div>
                        <ClientAssembly
                            :billid="billid"
                            bucketName="outer"
                            :aptitudeTables.sync="aptitudeTable"
                            :aptitudeSend.sync="aptitudeSend"
                            ref="client"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">审核历史</div>
                        <ComExaHistory
                            :billType="60481"
                            @getAuditHistory="getAuditHistory"
                            :tableData="tableData"
                            ref="ComExaHistory"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons
                :auditState="auditState"
                :state="parseInt(formData.state)"
                @exas="exas"
            />
            <el-button @click="cancel" size="small">取消</el-button>
        </div>
    </div>
</template>

<script>
// 注册地址
import SelectAddr from '@/components/common/addrComp'
// 审核
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
// 事实外包方
import correspondentUnit from '@/api/OutsourcingartyAdmin/correspondentUnit/correspondentUnit.js'
import ossRequest from '@/api/oss/oss.js'
// 委托人
import ClientAssembly from '@/pages/OutsourcingartyAdmin/factualOutsourcerAdmin/factoOutsourcerAssembly/clientAssembly'
//审核历史
import ComExaHistory from '@/components/common/exaHistory.vue'
// 按钮
import ComExaButtons from '@/components/common/exaButtons'
//审核
import examine from '@/api/OutsourcingartyAdmin/subcontractorAdmin/examine.js'
import {
    showSuccessPop,
    openAppClient,
    throttle,
    showLoading,
    hideLoading
} from '@/utils/common'
// 作废
import { toVoid } from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractor.js'
import { creditCodeVerification, isIdcard, isName } from '@/utils/rules'
export default {
    components: {
        SelectAddr,
        ComExaHistory,
        ComExaButtons,
        ClientAssembly
    },
    data () {
        return {
            tabsName: 'baseInfo',
            //表单数据
            formData: {
                address: '', //	注册地址
                businessLicenseOss: '', //	营业执照附件主键
                businessLicenseOssName: '', //营业执照
                creditCode: '', //统一信用代码
                deputy: '', //法人
                deputyOss: '', //法人附加主键
                deputyOssName: '', //法人身份附件名字
                id: '', //主键
                idCard: '', //法人身份证
                isOutOrg: '', //是否是库外单位（0 不是 1是)
                orgId: '', //机构id
                orgName: '', //机构名称
                outerName: '', //外包方名称
                registeredCapital: 0, //注册资本
                state: 0, //	单据状态
                type: 0, //外包方类型（0 分包商 1 供应商）
                dialogImageUrl: '', //法人附加主键路径
                businessLicenseOssImage: '' //营业执照附件路径
            },
            //类型列表
            typeList: [],
            payTaxesTypeList: [], //纳税类别列表

            firmPerformanceTable: [], //历史业绩数据
            firmPerformanceSend: false, //历史业绩是否验证成功

            isBaseSave: false, //基础是否保存
            alterationTable: [], //历史变更
            auditState: {}, //按钮状态
            newBaseData: {}, //处理过后的基础数据
            //是否为境外单位的单选
            radio: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            billid: '', //单据id
            winEvent: {}, //保存事件，跳转页面的时候，结束事件，优化性能
            lastConHeight: 0, //最后一个区域高度
            errorList: [], //错误标签
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            isIndeterminate: true,
            checkAll: false,
            tableData: [],
            // 事实外包方
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            bucketName: 'OutsourcingartyAdmin', //模块名
            relationId: '',
            aptitudeSend: false, //委托人验证是否通过
            aptitudeTable: [], //委托人
            oldEditData: [], //老数据
            // 审核对象
            commit: {
                billId: '', //	单据Id
                billType: 60481, //单据编码
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //	下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '' //审核意见
            },
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: creditCodeVerification,
                        trigger: 'blur'
                    }
                ],
                //外包方类别
                type: [
                    {
                        required: true,
                        message: '请选择外包方类别',
                        trigger: 'blur'
                    }
                ],
                //外包方名称
                outerName: [
                    {
                        required: true,
                        message: '请输入外包方名称',
                        trigger: 'change'
                    }
                ],
                //法人代表
                deputy: [
                    {
                        required: true,
                        validator: isName,
                        trigger: 'blur'
                    }
                ],
                //法人身份证号码
                idCard: [
                    {
                        required: true,
                        validator: isIdcard,
                        trigger: 'blur'
                    }
                ],
                //法人身份证附件
                deputyOssName: [
                    {
                        required: true,
                        message: '请上传法人身份证附件',
                        trigger: 'change'
                    }
                ],
                //注册资本
                registeredCapital: [
                    {
                        required: true,
                        message: '请输入注册资本',
                        trigger: 'blur'
                    }
                ],
                //营业执照
                businessLicenseOssName: [
                    {
                        required: true,
                        message: '请上传营业执照',
                        trigger: 'change'
                    }
                ],
                //注册地址
                address: [
                    {
                        required: true,
                        message: '请选择注册地址',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 102 - this.lastConHeight
        },
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    created () {
        this.billid = this.$route.query.billid
        // 历史业绩id
        this.formData.founderName = localStorage.getItem('userName')
        this.getBasicData() //获取基础数据
        this.getCurrentUnitInfo() //获取流程按钮
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'client',
            'firmPerformance',
            'firmAdmin',
            'evaluate',
            'auditHistory',
            'alteration',
            'accessory'
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        ...mapMutations(['setPopConfirm']),
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('accessoryCon')) {
                    const lastConHeight =
                        document.getElementById('accessoryCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        // 点击标签的方法
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
            this.queryData(e.name)
        },
        //根据点击不同的tab,调用不同的接口
        queryData (name) {
            switch (name) {
            // 基础信息
            case 'baseInfo':
                this.saveBase()
                this.saveBaseData()
                break
                //委托人
            case 'client':
                this.getAptitudeData()
                break
            }
        },
        //获取基本信息数据
        async getBasicData () {
            let res = await correspondentUnit.getCorrespondentUnitChange({
                id: this.billid
            })
            // 将数字转为字符串
            res.isOutOrg = res.isOutOrg + ''
            this.formData = res
            this.oldEditData = JSON.parse(JSON.stringify(res))
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //保存按钮
        async save () {
            this.errorList = []
            // 委托人
            this.$refs.client.preserve()
            this.saveBase() //基础信息验证
            if (this.isBaseSave && this.aptitudeSend) {
                Promise.all([
                    this.saveBaseData(), //基础信息
                    this.saveAptitude() //委托人
                ])
                    .then(async () => {
                        this.clientPop('suc', '保存成功')
                    })
                    .catch(() => {
                        this.scorllError()
                        this.clientPop('err', '保存失败')
                    })
            }
        },
        // 提交
        submit () {
            this.errorList = []
            // 委托人
            this.$refs.client.preserve()
            this.saveBase() //基础信息验证
            if (this.isBaseSave && this.aptitudeSend) {
                Promise.all([
                    this.saveBaseData(), //基础信息
                    this.saveAptitude() //委托人
                ])
                    .then(() => {
                        console.log(11111)
                        this.commit.billId = this.billid
                        subcontractorChange.findcommit(this.commit).then(() => {
                            this.clientPop('suc', '提交成功')
                            this.$router.replace('/FactualOutsourcer')
                        })
                    })
                    .catch(err => {
                        this.clientPop(err, '保存失败')
                        this.scorllError()
                    })
            }
        },
        //取消按钮
        cancel () {
            this.$router.replace('/FactualOutsourcer')
        },
        // 基础信息
        saveBase () {
            // 调用资质信息验证方法并将值传到父组件
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    // 如果外包商类型是数组则将数组转为字符串，否则不做处理
                    let datas = JSON.parse(JSON.stringify(this.formData))
                    this.newBaseData = datas
                    this.isBaseSave = true
                } else {
                    this.isBaseSave = false
                    this.setError('baseInfo')
                }
            })
        },
        // 基础数据保存
        saveBaseData () {
            return new Promise((resolve, reject) => {
                if (this.isBaseSave) {
                    correspondentUnit
                        .updateCorrespondentUnitChange(this.newBaseData)
                        .then(() => {
                            resolve()
                            this.getBasicData()
                        })
                        .catch(err => {
                            this.setError('baseInfo')
                            reject(err)
                        })
                }
            })
        },
        // 委托人删除
        async getAptitudeData (data) {
            // 如果有参数，则为删除时调用此方法，否则为保存
            if (data) {
                let data1 = []
                data1.push(data)
                await correspondentUnit.updateCorrespondentUnitDetailed(data1)
            } else {
                this.$refs.client.preserve()
                if (this.aptitudeTable.length > 0) {
                    await correspondentUnit.updateCorrespondentUnitDetailed(
                        this.aptitudeTable
                    )
                }
            }
            this.$refs.client.qualificationList(this.billid)
        },
        // 委托人保存
        saveAptitude () {
            return new Promise((resolve, reject) => {
                if (!this.aptitudeSend) {
                    return
                }
                correspondentUnit
                    .updateCorrespondentUnitChangeDetailed(this.aptitudeTable)
                    .then(() => {
                        resolve()
                        this.$refs.client.qualificationList(this.billid)
                    })
                    .catch(err => {
                        this.setError('client')
                        reject(err)
                    })
            })
        },
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    this.formData.deputyOssName = res[0].objectName
                    this.formData.deputyOss = res[0].relationId
                    this.formData.deputyOssImage = res[0].objectPath
                })
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //营业执照上传成功
        attachOnSuccessBl () {
            this.getObjectByRelationIdBl()
        },
        //获取上传成功的对象
        getObjectByRelationIdBl () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    // 等后端确定id和名字。再赋值
                    this.formData.businessLicenseOssName = res[0].objectName
                    this.formData.businessLicenseOss = res[0].relationId
                    this.formData.businessLicenseOssImage = res[0].objectPath
                })
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBeforeBl (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccessBl()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //预览法人附件
        preview1 () {
            if (this.formData.deputyOssImage) {
                window.open(this.formData.deputyOssImage)
            }
        },
        //营业执照预览附件
        preview2 () {
            if (this.formData.businessLicenseOssImage) {
                window.open(this.formData.businessLicenseOssImage)
            }
        },
        // // 审核历史列表查询
        async getAuditHistory () {
            let data = await subcontractorChange.findByIdAuditHistory({
                billId: this.billid,
                billType: 60481,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            this.tableData = data
        },
        // 去变更新增
        chengeNext () {
            let billid = this.billid
            this.$router.push({
                path: '/supplierbePutinstorageChangeAdd',
                query: { billid }
            })
        },
        // 审核
        audit () {
            this.errorList = []
            // 委托人
            this.$refs.client.preserve()
            this.saveBase() //基础信息验证
            if (this.isBaseSave && this.aptitudeSend) {
                Promise.all([
                    this.saveBaseData(), //基础信息
                    this.saveAptitude() //委托人
                ])
                    .then(async () => {
                        // 客户端弹窗弹出本地页面
                        openAppClient('/exaDialog', '填写审核意见', () => {
                            // 审核拿到审核弹窗的意见
                            const auditParams = JSON.parse(
                                localStorage.vuex
                            ).auditParams
                            // 将审核意见赋值给参数传给后端
                            examine
                                .audit({
                                    billId: this.$route.query.billid,
                                    billType: 60481,
                                    freeNextUnitIndex: 0,
                                    freeNextUser: '',
                                    isPass: auditParams.isPass,
                                    isShareInAudit: true,
                                    opinion: auditParams.opinion
                                })
                                .then(() => {
                                    this.clientPop('suc', '审核成功')
                                    // 返回列表
                                    this.cancel()
                                })
                        }, null, null, null, 'small')
                    })
                    .catch(() => {
                        this.clientPop('err', '保存失败')
                        this.scorllError()
                    })
            }
        },
        // 删除方法
        ctDelete () {
            this.clientPop('info', this.oneDeleteErr, this.delent)
        },
        //删除回调
        delent () {
            this.$Ajax
                .httpGet({
                    url: '/outer/facto/out/sourcer/delete/change',
                    params: {
                        id: this.billid
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.replace('/FactualOutsourcer')
                })
        },
        // 撤回
        withdrawChange () {
            this.clientPop('info', '是否确认撤回', this.callbackWithdraw)
        },
        // 撤回确认回调
        async callbackWithdraw () {
            let { code } = await examine.undoAudit({
                billId: this.billid, //单据id
                billType: '60481', //单据类型
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            if (code == 200) {
                showSuccessPop('撤回成功')
                // 返回列表
                this.cancel()
            } else {
                showSuccessPop('撤回失败')
            }
        },
        // 作废
        toVoidChange () {
            this.clientPop('info', '是否确认作废', this.callback)
        },
        async callback () {
            // 客户端弹窗弹出本地页面
            const auditParams = JSON.parse(localStorage.vuex).auditParams
            openAppClient('/nullifyDialog', '单据作废原因', async () => {
                showLoading()
                await toVoid({
                    billId: this.billid, //单据id
                    billType: '60481', //单据类型
                    nullifyCreated: '',
                    nullifyCreator: '',
                    nullifyCreatorId: '',
                    nullifyDescription: auditParams.nullifyDescription,
                    nullifyReason: auditParams.nullifyReason
                }).catch(() => {
                    this.clientPop('suc', '作废失败')
                })
                hideLoading()
            })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.withdrawChange() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.toVoidChange() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        // // 获取按钮状态
        getCurrentUnitInfo () {
            examine
                .getCurrentUnitInfo({
                    billId: this.billid,
                    billType: 60481,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
// 境外单位
::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
